package main

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"time"
)

type RntdSmses struct {
	Id        int64 `orm:"auto"`
	Balance   int64
	Status    int64
	CreatedAt time.Time `orm:"type(datetime)"`
	UpdatedAt time.Time `orm:"type(datetime)"`
}

type RntdSmsDetials struct {
	Id            int64  `orm:"auto"`
	PhoneNum      string `orm:"size(128)"`
	AppName       string `orm:"size(128)"`
	DeviceModel   string `orm:"size(128)"`
	SmsMessage    string `orm:"size(6)"`
	SmsMessageUrl string `orm:"size(128)"`
	SmsModelId    string `orm:"size(128)"`
	SmsToken      string `orm:"size(128)"`
	SmsStatus     int64
	CreatedAt     time.Time `orm:"type(datetime)"`
	UpdatedAt     time.Time `orm:"type(datetime)"`
}

func init() {

	orm.RegisterModel(new(RntdSmses))
	orm.RegisterModel(new(RntdSmsDetials))
	dbuser := "zhuozhengyun"
	dbpwd := "n89ZGAaWXsnEffW"
	dbname := "KXAPI-Server"
	dbhost := "rntd.cenisypym8o7.us-east-1.rds.amazonaws.com:3306"
	conn := dbuser + ":" + dbpwd + "@tcp(" + dbhost + ")/" + dbname + "?charset=utf8"
	orm.RegisterDataBase("default", "mysql", conn)
	orm.RunSyncdb("default", false, true)

	orm.Debug = true

	//自动建表
	name := "default"                          //数据库别名
	force := false                             //不强制建数据库
	verbose := true                            //打印建表过程
	err := orm.RunSyncdb(name, force, verbose) //建表
	if err != nil {
		fmt.Println(err)
	}
}

//插入短信发送记录
func InsertSmsDetial(detial *RntdSmsDetials) (id int64, err error) {
	o := orm.NewOrm()
	err = o.Begin()
	id, err = o.Insert(detial)
	if err != nil {
		o.Rollback()
	} else {
		o.Commit()
	}
	return

}

//更新短信记录
func UpdateSmsStatus(status *RntdSmses) (ustatus bool, unum int64, err error) {
	o := orm.NewOrm()
	err = o.Begin()
	info := RntdSmses{Id: status.Id,
		Balance:   status.Balance,
		Status:    status.Status,
		CreatedAt: status.CreatedAt,
		UpdatedAt: status.UpdatedAt}

	//	fmt.Println("-------->", info)
	if ustatus, unum, err = o.ReadOrCreate(&info, "Id"); err == nil {
		//		fmt.Println("剩余短信数量", unum)
		var num int64
		var cbanlance int64 = info.Balance
		if cbanlance <= 0 {
			status.Balance = status.Balance - 1
		} else {
			status.Balance = info.Balance - 1
		}

		if num, err = o.Update(status); err == nil {
			o.Commit()
			fmt.Println("Number of records updated in database:", num)
		} else {
			o.Rollback()
		}
	}

	return
}
